package com.shinewind.admin.controller;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.shinewind.common.constant.messageConstant;
import com.shinewind.common.util.FastDFSClientUtil;
import com.shinewind.home.service.IModelAdminService;
import com.shinewind.info.service.IInfoAdminService;
import com.shinewind.pojo.dto.AdminArticleDto;
import com.shinewind.pojo.dto.AdminModelDto;
import com.shinewind.pojo.entity.*;
import com.shinewind.pojo.result.Result;
import com.shinewind.pojo.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/admin")
@Api(value = "后台文章接口",description = "文章模块管理")
public class ArticleController {
    @DubboReference
    private IInfoAdminService iInfoAdminService;
    @DubboReference
    private IModelAdminService iModelAdminService;
    @Autowired(required = false)
    private FastDFSClientUtil fastDFSClientUtil;
    @Value("${fileServerUrl}")
    private String fileServerUrl;

    @GetMapping("/article/author/list")
    @ApiOperation(value = "查询所有作者信息",notes = "作者信息",response = Result.class)
    public PageVo<UserDetailVo> getAuthorListByPage(@RequestParam(value = "current",required = true) Integer current,
                                                    @RequestParam(value = "pageSize",required = true) Integer pageSize){
        //System.out.println("contentType:"+role);
        PageVo<UserDetailVo> authorList = iInfoAdminService.getArticleAuthorList(current,pageSize);
        return authorList;
    }

    @GetMapping("/article/author/keyword/list")
    @ApiOperation(value = "按关键字查询所有作者信息",notes = "关键字查询作者信息",response = Result.class)
    public PageVo<UserDetailVo> getAuthorListByPageAndKeyWord(@RequestParam(value = "current",required = true) Integer current,
                                                      @RequestParam(value = "pageSize",required = true) Integer pageSize,
                                                      @RequestParam(value = "keyword",required = false) String keyWord){
        //System.out.println("keyWord:"+keyWord);
        PageVo<UserDetailVo> authorList = iInfoAdminService.getArticleAuthorListByKeyWord(current,pageSize,keyWord);
        return authorList;
    }

    @GetMapping("/article/author/update/list")
    @ApiOperation(value = "查询所有作者信息",notes = "作者信息",response = Result.class)
    public Result getAuthorList(@RequestParam(value = "current",required = true) Integer current,
                                                    @RequestParam(value = "pageSize",required = true) Integer pageSize){
        //System.out.println("contentType:"+role);
        List<UserDetailVo> authorList = iInfoAdminService.getArticleAuthorUpdateList(current,pageSize);
        return Result.success(authorList,true,messageConstant.QUERY_SUCCESS);
    }

    @GetMapping("/article/list")
    @ApiOperation(value = "查询所有用户信息",notes = "用户所有信息",response = Result.class)
    public PageVo<AdminArticleListVo> getModelListByCondition(@RequestParam(value = "current",required = true) Integer current,
                                                            @RequestParam(value = "pageSize",required = true) Integer pageSize,
                                                            @RequestParam(value = "number",required = false) String title,
                                                            @RequestParam(value = "name",required = false) String author,
                                                            @RequestParam(value = "contentType",required = false) String publishTime){
        System.out.println("title:"+title);
        System.out.println("author:"+author);
        System.out.println("publishTime:"+publishTime);
        //查询除isModel外的信息
        List<AdminArticleListVo> articleVoList = iInfoAdminService.getArticleList(current,pageSize,title,
                author,publishTime);
        //查询isModel
        List<AdminArticleListVo> adminArticleListVos = articleVoList.stream().map(article ->{
            String isModel = iModelAdminService.getArticleStatusByMid(article.getMId());
            article.setIsModel(isModel);
            return article;
        }).collect(Collectors.toList());
        Integer total = adminArticleListVos.size();
        adminArticleListVos = ListUtil.page(current - 1,pageSize,adminArticleListVos);
        if(adminArticleListVos.size() > 0){
            return new PageVo<AdminArticleListVo>(adminArticleListVos,true, messageConstant.QUERY_SUCCESS,total);
        }
        else{
            return new PageVo<AdminArticleListVo>(null,false, messageConstant.QUERY_ERROR,total);
        }
    }

    @GetMapping("/article/detail/{aId}")
    @ApiOperation(value = "根据文章id查询详细信息",notes = "查询文章详细信息",response = Result.class)
    public Result getArticleInfoByAid(@PathVariable("aId") Integer aId){
        System.out.println("aId:"+aId);
        AdminArticleDetailVo adminArticleDetailVo = iInfoAdminService.getArticleByAid(aId);
        System.out.println("adminArticleDetailVo:"+adminArticleDetailVo);
        //查询isModel
        String isModel = iModelAdminService.getArticleStatusByMid(adminArticleDetailVo.getMId());
        adminArticleDetailVo.setIsModel(isModel);
        //查询商品图片
        if(isModel.equals("新闻")){
            String goodsUrl = iModelAdminService.getNewsInfo(adminArticleDetailVo.getMId()).getHref();
            adminArticleDetailVo.setGoodsUrl(goodsUrl);
        }
        else if(isModel.equals("模型")){
            //判断article中的mId在不在model表中
            Long count = iModelAdminService.getModelCount(adminArticleDetailVo.getMId());
            if(count > 0){
                String goodsUrl = iModelAdminService.getModelInfo(adminArticleDetailVo.getMId()).getHref();
                adminArticleDetailVo.setGoodsUrl(goodsUrl);
            }
            else{
                String goodsUrl = iModelAdminService.getNewsInfo(adminArticleDetailVo.getMId()).getHref();
                adminArticleDetailVo.setGoodsUrl(goodsUrl);
            }
        }
        return Result.success(adminArticleDetailVo,true,messageConstant.QUERY_SUCCESS);
    }

    @GetMapping("/article/model/list")
    @ApiOperation(value = "查询所有模型编号",notes = "作者信息",response = Result.class)
    public PageVo<AdminModelListVo> getModelMidListByPage(@RequestParam(value = "current",required = true) Integer current,
                                                    @RequestParam(value = "pageSize",required = true) Integer pageSize){
        //System.out.println("contentType:"+role);
        PageVo<AdminModelListVo> modelListVoPageVo = iModelAdminService.getModelMidList(current,pageSize);
        return modelListVoPageVo;
    }

    @GetMapping("/article/model/update/list")
    @ApiOperation(value = "查询所有模型编号",notes = "作者信息",response = Result.class)
    public Result getModelMidList(@RequestParam(value = "current",required = true) Integer current,
                                                          @RequestParam(value = "pageSize",required = true) Integer pageSize){
        //System.out.println("contentType:"+role);
        List<AdminModelListVo> modelListVoPageVo = iModelAdminService.getModelMidUpdateList(current,pageSize);
        return Result.success(modelListVoPageVo,true,messageConstant.QUERY_SUCCESS);
    }

    @GetMapping("/article/model/keyword/list")
    @ApiOperation(value = "按关键字查询所有模型编号",notes = "关键字查询模型编号",response = Result.class)
    public PageVo<AdminModelListVo> getModelMidListByPageAndKeyWord(@RequestParam(value = "current",required = true) Integer current,
                                                              @RequestParam(value = "pageSize",required = true) Integer pageSize,
                                                              @RequestParam(value = "keyword",required = false) String keyWord){
        //System.out.println("keyWord:"+keyWord);
        PageVo<AdminModelListVo> modelListVoPageVo = iModelAdminService.getModelMidListByKeyWord(current,pageSize,keyWord);
        return modelListVoPageVo;
    }

    @PostMapping("/article/add")
    @ApiOperation(value = "添加文章信息",notes = "添加文章信息",response = Result.class)
    public Result addUserInfo(@RequestBody AdminArticleDto adminArticleDto) throws Exception {
        System.out.println("adminArticleDto:"+adminArticleDto);
        //判断article类型
        if(adminArticleDto.getType().equals("新闻")){
            News news = iModelAdminService.addNewsInfo(adminArticleDto);
            //将信息写入article表中
            adminArticleDto.setMId(news.getId());
            Boolean flag = iInfoAdminService.addArticleInfo(adminArticleDto);
            if(flag){
                return Result.success(true,messageConstant.INSERT_SUCCESS);
            }
            else{
                return Result.fail(false,messageConstant.INSERT_ERROR);
            }
        }
        else{
            //将信息写入article表中
            Boolean flag = iInfoAdminService.addArticleInfo(adminArticleDto);
            if(flag){
                return Result.success(true,messageConstant.INSERT_SUCCESS);
            }
            else{
                return Result.fail(false,messageConstant.INSERT_ERROR);
            }
        }
    }

    @GetMapping("/article/info/{aId}/{type}")
    @ApiOperation(value = "根据文章id查询文章信息",notes = "查询文章信息",response = Result.class)
    public Result getArticleByAid(@PathVariable("aId") Integer aId,@PathVariable("type") String type){
        System.out.println("aId:"+aId);
        //从article表中查询信息
        Article article = iInfoAdminService.getArticleByaId(aId);
        //文章类型
        AdminArticleDto adminArticleDto = AdminArticleDto.builder().build();
        BeanUtils.copyProperties(article,adminArticleDto);
        adminArticleDto.setType(type);
        if(type.equals("新闻")){
            News news = iModelAdminService.getNewsInfo(adminArticleDto.getMId());
            adminArticleDto.setSrc(news.getSrc());
            adminArticleDto.setHref(news.getHref());
            UserInfo userInfo = iInfoAdminService.getUserInfo(article.getUId());
            adminArticleDto.setUName(userInfo.getNickName());
            adminArticleDto.setMName(news.getTitle());
        }
        if(ObjectUtil.isNotNull(adminArticleDto)){
            return Result.success(adminArticleDto,true,messageConstant.QUERY_SUCCESS);
        }
        return Result.fail(false,messageConstant.QUERY_ERROR);
    }

    @PostMapping("/article/update/{aId}")
    @ApiOperation(value = "修改文章信息",notes = "修改文章信息",response = Result.class)
    public Result UpdateArticle(@PathVariable("aId") Integer aId,@RequestBody AdminArticleDto adminArticleDto) throws Exception {
        System.out.println("adminArticleDto:"+adminArticleDto);
        //将信息写入article表中
        Boolean flag = iInfoAdminService.updateArticleInfo(aId,adminArticleDto);
        //将信息写入news表中
        if(adminArticleDto.getType().equals("新闻")){
            Boolean flag2 = iModelAdminService.updateNewsInfo(adminArticleDto);
            if(flag2){
                return Result.success(true,messageConstant.UPDATE_SUCCESS);
            }
            else{
                return Result.fail(false,messageConstant.UPDATE_ERROR);
            }
        }
        return Result.success(true,messageConstant.UPDATE_SUCCESS);
    }

    @DeleteMapping("/article/delete/{aId}/{type}")
    @ApiOperation(value = "删除文章信息",notes = "删除文章信息",response = Result.class)
    public Result DeleteArticle(@PathVariable("aId") Integer aId,@PathVariable("type") String type) throws Exception {
        //将信息写入article表中
        Boolean flag = iInfoAdminService.DeleteArticleByAid(aId);
        if(flag){
            if(type.equals("新闻")){
                //查询id
                AdminArticleDetailVo article = iInfoAdminService.getArticleByAid(aId);
                Boolean flag2 = iModelAdminService.deleteNewsByid(article.getMId());
                if(flag2){
                    return Result.success(true,messageConstant.DELETE_SUCCESS);
                }
                return Result.fail(false,messageConstant.DELETE_ERROR);
            }
            return Result.success(true,messageConstant.DELETE_SUCCESS);
        }
        else{
            return Result.fail(false,messageConstant.DELETE_ERROR);
        }
    }

    @PostMapping("/article/download")
    @ApiOperation(value = "下载文件",notes = "下载excel文件",response = Result.class)
    public void downLoadFile(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //查询除isModel外的信息
        List<AdminArticleListVo> articleVoList = iInfoAdminService.getArticleList(0,0,null,
                null,null);
        //查询isModel
        List<AdminArticleListVo> adminArticleListVos = articleVoList.stream().map(article ->{
            String isModel = iModelAdminService.getArticleStatusByMid(article.getMId());
            article.setIsModel(isModel);
            return article;
        }).collect(Collectors.toList());
        //生成excel文件
        File file = new File("");
        String filePath = file.getCanonicalFile() + File.separator + "model_player_admin\\src\\main\\resources\\article.xlsx";
        // 设置下载弹窗的文件名和格式（文件名要包括名字和文件格式）
        ExcelWriter writer = null;
        resp.setCharacterEncoding("utf-8");
        resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("article.xlsx", "UTF-8"));
        resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        // 响应类型,编码
        resp.setContentType("application/octet-stream;charset=utf-8");
        OutputStream out = resp.getOutputStream();
        if(FileUtil.exist(filePath) == true){
            writer = ExcelUtil.getWriter();
            writer.renameSheet("文章列表");
            writer.addHeaderAlias("aId","文章编号");
            writer.addHeaderAlias("nickName","作者");
            writer.addHeaderAlias("content","内容");
            writer.addHeaderAlias("watch","浏览数");
            writer.addHeaderAlias("isModel","文章类型");
            writer.addHeaderAlias("publishTime","发布时间");
            writer.write(adminArticleListVos,true);
        }
        else{
            new File(filePath).createNewFile();
            writer = ExcelUtil.getWriter();
            writer.renameSheet("文章列表");
            writer.addHeaderAlias("aId","文章编号");
            writer.addHeaderAlias("nickName","作者");
            writer.addHeaderAlias("content","内容");
            writer.addHeaderAlias("watch","浏览数");
            writer.addHeaderAlias("isModel","文章类型");
            writer.addHeaderAlias("publishTime","发布时间");
            writer.write(adminArticleListVos,true);
        }
        writer.flush(out);
        out.flush();
        writer.close();
        // 关闭流对象
        IoUtil.close(out);
    }
}
